package com.other;

import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by baiguantao on 2017/11/24.
 */
public class IpUtils {
    public static void main(String[] args) {
        System.out.println(getLocalIPList());

    }

    /**
     * 简单获取本机第一个ip地址
     * @return
     */
    public String getFirstIp(){
        InetAddress address = null;//获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
        try {
            address = InetAddress.getLocalHost();
            String hostAddress = address.getHostAddress();
            System.out.println(hostAddress);
            return hostAddress;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "未知ip";
    }

    /**
     * 获取ip地址列表
     * @return
     */
    public static List<String> getLocalIPList() {
        List<String> ipList = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            String ip;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();
                inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                        ip = inetAddress.getHostAddress();
                        ipList.add(ip);
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
            ipList.add("未知ip");
            return ipList;
        }
        return ipList;
    }

}
